package ils.util;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class Util
{
    private static final Logger logger          = LoggerFactory.getLogger(Util.class);
    private static MessageDigest messageDigest;

    public static final int DAY = 1000*60*60*24; // number of milliseconds in a day

    public static void copy(Object dest, Object org)
    {
        try
        {
            BeanUtils.copyProperties(dest, org);
        }
        catch (Exception e)
        {
            logger.error("Some exception while copying properties",e);
        }
    }
    public static String md5(String input)
    {
        byte[] array = messageDigest.digest(input.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
          sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
        }
        return sb.toString();
    }

    public static String randomString(int length)
    {
        String str = "";
        while (str.length() < length)
        {
            str = str + UUID.randomUUID().toString().replace('-','A');
        }
        return str.substring(0, length);
    }

    public static double format(double value, int places){
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    public static String formatToDate(Date date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
        return simpleDateFormat.format(date);
    }

    static
    {
        try
        {
            messageDigest = MessageDigest.getInstance("MD5");
        }
        catch (NoSuchAlgorithmException e)
        {
           logger.error("count not instantiate Message Digest for MD5", e);
        }
    }
}
